#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <assert.h>
#include <fstream>
#include <mutex>
#include <algorithm>
#include <jsoncpp/json/json.h>

#include "oj_model.hpp"
#include "../Comm/Log.hpp"
#include "../Comm/util.hpp"
#include "oj_view.hpp"
//#include "../Comm/httplib.h"

namespace ns_control
{
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;

    class Machine
    {
    public:
        std::string ip;
        int port;
        uint32_t load;
        std::mutex *mtx; // mutex禁止拷贝，所以使用指针，保护修改load时的安全

    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {}
        ~Machine() {}

    public:
        // 更新负载数量
        void IncLoad()
        {
            if (mtx)  mtx->lock();
            ++load;
            if (mtx) mtx->unlock();
        }

        void DecLoad()
        {
            if (mtx)  mtx->lock();
            --load;
            if (mtx) mtx->unlock();
        }
        // 获取一个主机的load
        uint32_t GetLoad()
        {
            uint32_t ret;
            if (mtx)  mtx->lock();
            ret = load;
            if (mtx) mtx->unlock();

            return ret;
        }
    };

    const std::string SerMach_confpath = "./machine_conf/server_machine.conf";
    
    // 负载均衡模块
    class LoadBlance
    {
    private:
        // 下标充当主机编号
        std::vector<Machine> machines;

        // 在线主机的编号
        std::vector<int> onlinemachine;

        // 离线主机的编号
        std::vector<int> offlinemachine;

        // 保护在选择主机的时候的安全
        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(Loadconf(SerMach_confpath));
            LOG(INFO, "加载 machine_conf 成功");
        }
        ~LoadBlance() {}

    public:
        // 加载配置文件
        bool Loadconf(const std::string &SerMach_confpath)
        {
            std::ifstream in(SerMach_confpath);
            if (!in.is_open())
            {
                LOG(FATAL, "加载 %s 失败", SerMach_confpath.c_str());
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::Splitstring(line, ":", &tokens);
                if (tokens.size() != 2)
                {
                    LOG(WARNING, "切分 %s 失败", line.c_str());
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = std::stoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();

                onlinemachine.push_back(machines.size());
                machines.push_back(std::move(m));
            }

            in.close();
            return true;
        }

        // 两个参数都是输出型  智能选择负载最小的主机
        bool SmartChoice(int *id, Machine **m)
        {
            // 轮询+hash
            mtx.lock();
            
            int num = onlinemachine.size();
            if (num == 0){
                mtx.unlock();
                LOG(FATAL, "所有主机全部离线了");
                return false;
            }
            *id = onlinemachine[0];
            *m = &machines[onlinemachine[0]];
            uint32_t minload = machines[onlinemachine[0]].GetLoad();
            for (int i = 1; i < num; i++)
            {
                if (minload > machines[onlinemachine[i]].GetLoad())
                {
                    minload = machines[onlinemachine[i]].GetLoad();
                    *id = onlinemachine[i];
                    *m = &machines[onlinemachine[i]];
                }
            }

            mtx.unlock();
            return true;
        }
        // 将指定主机离线
        void OfflineMachine(int id)
        {
            mtx.lock();
            for (auto iter = onlinemachine.begin(); iter != onlinemachine.end(); iter++)
            {
                if (*iter = id)
                {
                    onlinemachine.erase(iter);
                    offlinemachine.push_back(id);
                    break;
                }
            }
            mtx.unlock();
        }
        // 机器上线
        void OnlinMachine()
        {
            //我们统一上线，后面统一解决
            mtx.lock();
            onlinemachine.insert(onlinemachine.end(), offlinemachine.begin(), offlinemachine.end());
            offlinemachine.erase(offlinemachine.begin(), offlinemachine.end());
            mtx.unlock();

            LOG(INFO,"所有的主机有上线啦!");
        }

        // //for test
        // void ShowMachines()
        // {
        //     mtx.lock();
        //     std::cout << "当前在线主机列表: ";
        //     for(auto &id : onlinemachine)
        //     {
        //         std::cout << id << " ";
        //     }
        //     std::cout << std::endl;
        //     std::cout << "当前离线主机列表: ";
        //     for(auto &id : offlinemachine)
        //     {
        //         std::cout << id << " ";
        //     }
        //     std::cout << std::endl;
        //     mtx.unlock();
        // }
    };

    class Control
    {
    private:
        Model _model;            // 提供后台数据
        View _view;              // 渲染html网页
        LoadBlance _load_blance; // 负载均衡器
    public:
        Control(){}
        ~Control(){}
    public:
        // 获取题目列表，构建为网页信息返回
        bool Allquestion(std::string *html)
        {
            bool ret = true;
            std::vector<Question> all_questions;
            if (_model.GetAllQuestions(&all_questions)){
                sort(all_questions.begin(), all_questions.end(), [](const Question &q1, const Question &q2)
                     { return std::stoi(q1.number) < std::stoi(q2.number); });

                // 将获取的all_questions构建为html返回
                _view.expandallhtml(all_questions, html);
            }
            else{
                *html = "题目列表不存在";
                ret = false;
            }

            return ret;
        }
        bool Numberquestion(const std::string& number, std::string *html)
        {
            bool ret = true;
            Question q;
            if (_model.GetOneQuestion(number, &q)){
                // 将获取的题目构建一个网页返回
                _view.expandonehtml(q, html);
            }
            else{
                *html = "指定题目" + number + "不存在";
                ret = false;
            }

            return ret;
        }

        void judge(const std::string& number, const std::string &in_json, std::string *out_json)
        {

            // 0. 获取指定的题目的详情
            Question q;
            _model.GetOneQuestion(number, &q);

            // 1. 将in_json反序列化拿到题目 id  code input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);

            // 2. 将code与测试用例代码拼接
            std::string code_string = in_value["code"].asString();
            Json::Value complie_value;

            complie_value["input"] = in_value["input"].asString();
            complie_value["code"] = code_string + "\n" + q.tail;
            complie_value["cpu_limit"] = q.cpu_limit;
            complie_value["mem_limit"] = q.mem_limit;
            
            Json::FastWriter writer;
            std::string complie_string = writer.write(complie_value);

            // 3. 负载均衡的选择一台主机
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_blance.SmartChoice(&id, &m))
                {
                    // 主机全部已经离线
                    break;
                }
                LOG(INFO, "选择主机成功,id:%d  ip:%s  port:%d", id, m->ip.c_str(), m->port);
                // 4. 向该主机发送http请求
                m->IncLoad();  //选择的主机的负载++
                httplib::Client cli(m->ip, m->port);
                if (auto res = cli.Post("/compile_and_run", complie_string, "application/json;charset=utf-8"))
                {
                    // 请求成功
                    if (res->status == 200){
                        *out_json = res->body;

                        m->DecLoad();
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(INFO, "该主机,id:%d  ip:%s  port:%d 已经掉线", id, m->ip.c_str(), m->port);
                    _load_blance.OfflineMachine(id);
                    
                    //for debug
                    //_load_blance.ShowMachines();
                }
            }
        }
    };
}